package it.fuesi.synotools.adapters;

import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import it.fuesi.synotools.R;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.helpers.LayoutHelper;
import it.fuesi.synotools.model.filestation.FileStationClientParameters;
import it.fuesi.synotools.model.filestation.FileStationFile;
import it.fuesi.synotools.model.filestation.FileStationListDataObject;
import it.fuesi.synotools.services.tasks.filestation.FileStationList;

/**
 * Created by pascotto on 16/10/14.
 */
public class FileStationFilesAdapter extends SynoAdapter<FileStationListDataObject>{

        protected static final String TAG = "DownloadTasksAdapter";

        protected List<FileStationFile> data;
        private Context context;
        private Fragment fragment;
        private LayoutInflater inflater;
        private FileStationClientParameters lastUsedParameters;
        private int files = 0;
        private int folders = 0;
        private long totalSize = 0;
        private boolean selectionMode = false;

        private OnItemChecked mItemCheckedListener;

        public interface OnItemChecked{
            public void onItemChecked();
        }

        public void setOnItemCheckedEventListener(OnItemChecked eventListener) {
            mItemCheckedListener=eventListener;
        }

        public boolean isSelectionMode() {
            return selectionMode;
        }

        public void setSelectionMode(boolean selectionMode) {
            this.selectionMode = selectionMode;
        }

        public int getFiles() {
            return files;
        }

        public int getFolders() {
            return folders;
        }

        public long getTotalSize() {
            return totalSize;
        }


        public void setCurrentFolder(String currentFolder){
            lastUsedParameters = FileStationClientParameters.build(true);
            lastUsedParameters.setFolder_path(currentFolder);
        }

        public String goToParent(){
                if (lastUsedParameters != null){
                  final String current_folder = lastUsedParameters.getFolder_path();
                  final FileStationClientParameters params = FileStationClientParameters.build(false);
                  Log.d(TAG, "CurrentFolderPath: " + current_folder);

                  final String parentFolderPath;
                  if(current_folder == null || current_folder.isEmpty() || current_folder.indexOf("/")<0)
                      parentFolderPath = null;
                  else
                      parentFolderPath = current_folder.substring(0, current_folder.lastIndexOf("/"));
                  Log.d(TAG, "ParentFolderPath: " + parentFolderPath);
                    params.setFolder_path(parentFolderPath);
                  fetch(params);
                  return parentFolderPath;
                }

                return "/";
        }

        public String getCurrentFolder(){
            if(lastUsedParameters != null)
                return lastUsedParameters.getFolder_path();
            else
                return "/";
        }

        public String getCurrentFolderName(){
            final String currentFolder = getCurrentFolder();
            return currentFolder.substring(currentFolder.lastIndexOf("/")+1);
        }

        public String getCurrentFolderParent(){
            final String currentFolder = getCurrentFolder();
            return currentFolder.substring(0, currentFolder.lastIndexOf("/"));
        }

        @Override
        public Context getContext(){
            return this.context;
        }

        public FileStationFilesAdapter(LayoutInflater inflater, List<FileStationFile> data, Context context, Fragment fragment)  {
            this.data = data;
            this.context=context;
            this.fragment=fragment;
            this.inflater = inflater;
        }

        private List<FileStationFile> reorder(List<FileStationFile> files){
            this.files = 0;
            this.folders = 0;
            this.totalSize = 0;

            if(files == null) return files;

            final List<FileStationFile> list = new ArrayList<FileStationFile>();

            for(FileStationFile file : files){
                if(file.isdir()) {
                    list.add(file);
                    this.folders++;
                }
            }

            for(FileStationFile file : files){
                if(!file.isdir()) {
                    list.add(file);
                    this.files++;
                    this.totalSize += file.getSize();
                }
            }

            return list;


        }



        @Override
        public void setItemCollection(FileStationListDataObject data){
            this.data = reorder(data.getFiles() != null ? data.getFiles() : data.getShares());
            notifyDataSetChanged();
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            return data != null ? data.size() : 0;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int index) {
            if(data != null && data.size() > index) {
                return data.get(index);
            }
            return null;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int id) {
            return id;
        }


        private class ViewHolder {
            String mPath;
            TextView mFileName;
            CheckBox check;
            ImageView mFileIcon;
            TextView mFileSize;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if(convertView==null){
                convertView = inflater.inflate(R.layout.file_station_item, null);


            Log.d(TAG, "getView --> displaying item: " + position);

            holder = new ViewHolder();
            holder.check = (CheckBox)convertView.findViewById(R.id.file_check);
            holder.mFileName = (TextView)convertView.findViewById(R.id.file_name);
            holder.mFileSize = (TextView)convertView.findViewById(R.id.file_size);
            holder.mFileIcon = (ImageView)convertView.findViewById(R.id.file_icon);
            convertView.setTag(holder);

            holder.check.setVisibility(isSelectionMode() ? View.VISIBLE : View.GONE);

            holder.check.setOnClickListener( new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v ;
                    FileStationFile file = (FileStationFile) cb.getTag();
                    file.setSelected(cb.isChecked());
                    mItemCheckedListener.onItemChecked();
                }
            });
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

            LayoutHelper.manageGridItemBackground(getContext(), convertView, position);


            final FileStationFile file = data.get(position);
            holder.mPath = file.getPath();
            holder.mFileName.setText(file.getName());
            holder.mFileSize.setText(FormatHelper.formatFileSize(file.getSize()));
            if(file.isdir())
                holder.mFileIcon.setImageResource(R.drawable.folder);
            else
                holder.mFileIcon.setImageResource(R.drawable.document); //TODO: manage mime type

            //holder.check.setVisibility(isSelectionMode() && !file.isdir() ? View.VISIBLE : View.GONE);
            holder.check.setVisibility(isSelectionMode() ? View.VISIBLE : View.GONE);

            holder.check.setTag(file);

            holder.check.setChecked(file.isSelected());

            return convertView;
        }


        public void fetch(){
            if(lastUsedParameters != null)
                lastUsedParameters.setRefreshCache(false);
            fetch(lastUsedParameters);
        }

        public void fetch(FileStationClientParameters params){
            lastUsedParameters = params;
            new FileStationList(this).execute(params);
        }




    public Set<String> getSelections() {
        final Set<String> set = new HashSet<String>();

        for(FileStationFile file : data){
            if(file.isSelected())
                set.add(file.getPath());
        }
        return set;
    }


}
